/**
 * Created by lwh on 2016/9/28.
 */
'use strict';
var app = angular.module('myApp', ['ui.bootstrap', 'services']);
angular.module('services', ['ngResource', 'ngCookies']);

app.value('globalVar', {
    accessToken: 'L0xgSLWWWVxL',
    // backendUrl: 'http://localhost:8080/api'
    backendUrl: '../maternity/api'
});

app.controller('recordCtrl', ['$scope', 'RecordService', '$cookies', 'globalVar', function ($scope, RecordService, $cookies, globalVar) {
    var cur_page = 1;
    $scope.pages = [];

    function updateData() {
        if (GetQueryString("mid") == null) {
            return
        }
        $scope.mid = parseInt(GetQueryString("mid"));

        RecordService.getRecords({mid: $scope.mid, page: cur_page, perPage: 10}, function (result) {
            if (result.success) {
                $scope.pages = [];
                var totalPage = Math.ceil(result.data.total / 10);
                if (totalPage == 0)
                    totalPage++;
                for (var i = 0; i < totalPage; i++) {
                    $scope.pages.push(i + 1);
                }
                $scope.records = result.data.records;
                angular.forEach($scope.records, function (obj) {
                    obj.start = new Date(obj.start * 1000);
                    obj.start.setHours(0, 0, 0, 0);
                    obj.end = new Date(obj.end * 1000);
                    obj.end.setHours(0, 0, 0, 0);
                    obj.create_date = new Date(obj.create_date * 1000);
                    obj.create_date.setHours(0, 0, 0, 0);
                    obj.duration = (obj.end - obj.start) / (24 * 3600 * 1000)+1;
                    obj.temp = [];
                    for (var j = 0; j < obj.grade; j++)
                        obj.temp.push(j);
                });
            } else {
                console.log(result.code);
                switch (result.code) {

                }
            }
        });
    }

    $scope.$on('addRecordSuccess', function () {
        cur_page = 1;
        updateData();
    });

    //设置当前选中页样式
    $scope.isActivePage = function (page) {
        return cur_page == page;
    };
    //上一页
    $scope.previous = function () {
        $scope.selectPage(cur_page - 1);
    };
    //下一页
    $scope.next = function () {
        $scope.selectPage(cur_page + 1);
    };

    //选择页面
    $scope.selectPage = function (page) {
        if ($scope.pages.indexOf(page) != -1) {
            cur_page = page;
            return;
        }
        updateData();
    };
    $scope.selectPage(1);
}]);

app.controller('navCtrl', function ($scope, UserService) {
    UserService.getCurrentUserBaseInfo(function (result) {
        if (result.success) {
            $scope.name = result.data.name;
        } else {
            switch (result.code) {
                case 101:
                    location.href = "login.html";
            }
        }
    })
});

app.controller('addRecordCtrl', function ($scope, $rootScope, RecordService) {
    $scope.mid = parseInt(GetQueryString("mid"));
    if ($scope.mid == null)
        return;
    // 日历配置
    $scope.today = new Date();
    $scope.today.setHours(0, 0, 0, 0);
    $scope.year = $scope.today.getFullYear();
    $scope.month = $scope.today.getMonth();
    function updateCalendar() {
        $scope.selectedMonthCalendar = getCalendar($scope.year, $scope.month);
        $scope.nextMonthCalendar = getCalendar($scope.year, $scope.month + 1);
    }

    updateCalendar();
    $scope.onYearChange = function () {
        console.log($scope.year)
    };
    $scope.onMonthChange = function () {

    };
    $scope.nextMonth = function () {
        $scope.month++;
        $scope.year += Math.floor($scope.month / 12);
        $scope.month = ($scope.month + 12) % 12;
        updateCalendar();
    };
    $scope.preMonth = function () {
        $scope.month--;
        $scope.year += Math.floor($scope.month / 12);
        $scope.month = ($scope.month + 12) % 12;
        updateCalendar();
    };
    $scope.preYear = function () {
        $scope.year--;
        updateCalendar();
    };
    $scope.nextYear = function () {
        $scope.year++;
        updateCalendar();
    };
    $scope.isToday = function (date) {
        return date.getTime() === $scope.today.getTime();
    };
    $scope.inSelectedMonth = function (date) {
        return date.getFullYear() === $scope.year && date.getMonth() === $scope.month;
    };
    $scope.inNextMonth = function (date) {
        return date.getFullYear() === $scope.year + Math.floor(($scope.month + 1) / 12) && date.getMonth() === ($scope.month + 1) % 12;
    };
    $scope.isServeDay = function (date) {
        if ($scope.startDate instanceof Date && $scope.endDate instanceof Date)
            return $scope.startDate.getTime() <= date.getTime() && date.getTime() <= $scope.endDate.getTime();
        else
            return false;
    };
    $scope.setStartDate = function (date) {
        $scope.startDate = date;
        updateEndDate();
    };
    $scope.setEndDate = function (date) {
        $scope.endDate = date;
    };
    function getCalendar(year, month) {
        var firstDayInMonth = new Date(year, month, 1);
        var firstDayInFirstWeek = new Date(year, month, 1 - firstDayInMonth.getDay());
        var lastDayInMonth = new Date(year, month + 1, 0);
        var totalDay = firstDayInMonth.getDay() + lastDayInMonth.getDate() + 6 - lastDayInMonth.getDay();
        var dates = new Array(totalDay / 7);
        for (var i = 0; i < dates.length; i++) {
            dates[i] = new Array(7);
        }
        for (var j = 0; j < totalDay; j++) {
            dates[Math.floor(j / 7)][j % 7] = new Date(firstDayInFirstWeek.getFullYear(), firstDayInFirstWeek.getMonth(), firstDayInFirstWeek.getDate() + j);
        }
        return dates;
    }

    // 日历配置结束

    function init() {
        $scope.startDate = null;
        $scope.endDate = null;
        $scope.durationSet = [
            {
                value: 26,
                checked: false
            },
            {
                value: 42,
                checked: false
            },
            {
                value: 52,
                checked: false
            },
            {
                value: null,
                checked: false
            }
        ];
        $scope.familyTypeSet = [
            {
                value: "双外籍人士",
                checked: false
            },
            {
                value: "单外籍人士",
                checked: false
            },
            {
                value: "单亲家庭",
                checked: false
            },
            {
                value: "多月嫂协作",
                checked: false
            },
            {
                value: "无母亲陪护",
                checked: false
            }
        ];
        $scope.grade = 0;
        $scope.hoverIndex = -1;
        $scope.employer = "";
        $scope.idNum = "";
        $scope.phone = "";
        $scope.address = "";
        $scope.babyNum = "";
        $scope.comment = "";
    }

    init();

    $scope.setGrade = function (grade) {
        $scope.grade = grade;
    };

    $scope.setHoverIndex = function (hoverIndex) {
        $scope.hoverIndex = hoverIndex;
    };

    $scope.setDuration = function (duration) {
        angular.forEach($scope.durationSet, function (d) {
            if (d === duration)
                return;
            d.checked = false;
        });
        updateEndDate();
    };

    $scope.onCustomDurationChange = function () {
        var customDuration = $scope.durationSet[$scope.durationSet.length - 1];
        if (parseInt(customDuration.value) < 1 || customDuration.value == '-')
            customDuration.value = 1;
        updateEndDate();
    };

    function updateEndDate() {
        if ($scope.startDate instanceof Date) {
            $scope.endDate = null;
            for (var i = 0; i < $scope.durationSet.length; i++) {
                if ($scope.durationSet[i].checked) {
                    $scope.endDate = new Date($scope.startDate.getFullYear(),
                        $scope.startDate.getMonth(),
                        $scope.startDate.getDate() + $scope.durationSet[i].value - 1);
                    break;
                }
            }
        }
    }

    $scope.showAddRecordForm = function () {
        //$("#" + __method.calendarId).css('display', 'block');
        $scope.showForm = true;
    };

    $scope.save = function () {
        var data = {};
        if ($scope.employer == null || $scope.employer == '') {
            alert("雇主姓名不能为空");
            return;
        }
        if (!/^\d{17}(\d|X)$/.test($scope.idNum)) {
            alert("请输入正确的身份证号");
            return;
        }
        if (!/^1\d{10}$/.test($scope.phone)) {
            alert("请输入11位手机号码");
            return;
        }
        if ($scope.address == null || $scope.address == '') {
            alert("家庭住址不能为空");
            return;
        }
        if ($scope.babyNum == null || isNaN(parseInt($scope.babyNum)) || parseInt($scope.babyNum) < 1) {
            alert("宝宝数量至少为1");
            return;
        }
        if ($scope.comment == null || $scope.comment == '') {
            alert("评价内容不能为空");
            return;
        }
        if ($scope.grade == null || isNaN(parseInt($scope.grade)) || parseInt($scope.grade) < 1 || parseInt($scope.grade) > 5) {
            alert("评分范围为1~5");
            return;
        }
        if ($scope.endDate == null) {
            alert("请指定服务周期");
            return;
        }
        if ($scope.startDate == null) {
            alert("请选择服务开始日期");
            return;
        }
        var familyType = "";
        angular.forEach($scope.familyTypeSet, function (type) {
            if (type.checked)
                familyType += (type.value + ",");
        });
        familyType = familyType.substring(0, familyType.length - 1);

        data.employer = $scope.employer;
        data.id_num = $scope.idNum;
        data.phone = $scope.phone;
        data.address = $scope.address;
        data.baby_num = $scope.babyNum;
        data.family_type = familyType;
        data.grade = $scope.grade;
        data.start = $scope.startDate.getTime() / 1000;
        data.end = $scope.endDate.getTime() / 1000;
        data.comment = $scope.comment;
        data.mid = $scope.mid;

        RecordService.addRecord(data, function (result) {
            if (result.success) {
                alert("添加成功");
                init();
                $scope.showForm = false;
                $rootScope.$broadcast('addRecordSuccess')
            } else {
                alert(result.msg);
                switch (result.code) {
                }
            }
        });

        $scope.showForm = false;
    };

    $scope.cancel = function () {
        init();
        $scope.showForm = false;
    };
});

app.controller('baseInfoCtrl', ['$scope', 'MaternityService', 'globalVar', function ($scope, MaternityService) {
    if (GetQueryString("mid") == null) {
        alert("无效月嫂");
        location.href = "no-matron.html";
        return
    }
    $scope.mid = parseInt(GetQueryString("mid"));
    MaternityService.getBaseInfo({mid: $scope.mid}, function (result) {
        if (result.success) {
            $scope.info = result.data;
        } else {
            alert(result.msg);
            switch (result.code) {
                case 201:
                    location.href = "no-matron.html";
            }
        }
    });
    MaternityService.getGradePoints({mid: $scope.mid}, function (result) {
        $scope.grade = new Array(result.data.length + 1);
        var totalPoint = 0;
        var gradeCount = 0;
        angular.forEach(result.data, function (grade) {
            $scope.grade[grade.p] = grade.n;
            totalPoint += (grade.p * grade.n);
            gradeCount += grade.n;
        });
        $scope.avgGrade = totalPoint / gradeCount;
    })
}]);
